package com.dl.mall.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.util.SaResult;
import com.dl.mall.utils.result.Result;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * SaToken未登录异常
 * @author DL
 * @create 2022-04-07 10:49
 */
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalNotLoginException {

    @ResponseBody
    @ExceptionHandler(NotLoginException.class)
    public Result handlerException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        // 打印堆栈，以供调试
        System.out.println("SaToken未登录异常---------------");
        nle.printStackTrace();

        // 判断场景值，定制化异常信息
        String message = "";
        switch (nle.getType()) {
            case NotLoginException.NOT_TOKEN:
                message = "您未提供token";
                break;
            case NotLoginException.INVALID_TOKEN:
                message = "您的token无效";
                break;
            case NotLoginException.TOKEN_TIMEOUT:
                message = "您的token已过期";
                break;
            case NotLoginException.BE_REPLACED:
                message = "您的token已被顶下线";
                break;
            case NotLoginException.KICK_OUT:
                message = "您的token已被踢下线";
                break;
            default:
                message = "当前会话未登录";
                break;
        }

        // 返回给前端
        return Result.error(message).code(403);
    }

}
